package com.tc.activiti.user.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tc.activiti.activiti.util.BeanUtils;
import com.tc.activiti.activiti.util.CurrentContextUtil;
import com.tc.activiti.base.constants.PageConstants;
import com.tc.activiti.base.constants.StateEnum;
import com.tc.activiti.base.entity.APIResult;
import com.tc.activiti.base.web.GenericController;

import com.tc.activiti.user.entity.SysUser;
import com.tc.activiti.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @author zengqingfa
 * @date 2019/10/18 15:40
 * @description
 * @email zengqingfa_java@163.com
 */
@Api(tags = "人员管理", value = "人员管理")
@RestController
@RequestMapping("/user")
public class UserController extends GenericController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;


    @RequestMapping("/findAll")
    @ResponseBody
    public List<SysUser> findAll() {
        List<SysUser> userList = userService.findAll();
        return userList;
    }


    /**
     * 登录系统
     *
     * @param username
     * @param password
     * @return
     */
    @ApiOperation(value = "登录", notes = "登录")
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public APIResult login(String username, String password) {
        APIResult result = new APIResult<>();
        try {
            logger.debug("login request: {username={}, password={}}", username, password);
            //先查找是否有这个用户
            SysUser user = userService.findByUsername(username);
            if (BeanUtils.isEmpty(user)) {
                throw new RuntimeException("用户不存在");
            }
            //判断密码
            if (!password.equals(user.getPassword())) {
                throw new RuntimeException("用户密码不正确");
            }
            //把用户信息存入到threadLocal
            CurrentContextUtil.getCurrentUserContext().set(user);
            //用户信息存入session
            HttpSession session = getRequest().getSession();
            session.setAttribute("user", user);
            result.setMessage("登录成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_PERSON.getCode());
            result.setMessage(StateEnum.ERROR_PERSON.getText());
            result.setCause(e.getMessage());
            logger.error("/user/login", e);
        }
        return result;
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        CurrentContextUtil.getCurrentUserContext().remove();
        return "sendRedirect:/login.html";
    }


    @ApiOperation(value = "人员分页列表", notes = "人员分页列表")
    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    @ResponseBody
    public APIResult<PageInfo> findByPage(@RequestParam("currentPage") Integer pageNo, @RequestParam Integer pageSize) {
        APIResult<PageInfo> result = new APIResult<>();
        if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
        if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
        try {
            //使用分页插件
            PageHelper.startPage(pageNo, pageSize);
            List<SysUser> userList = userService.findAll(); //获取后台数据列表
            //根据查询的数据列表，得到分页的结果对象
            PageInfo pageInfo = new PageInfo(userList);
            result.setData(pageInfo);
            result.setMessage("查询人员成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_PERSON.getCode());
            result.setMessage(StateEnum.ERROR_PERSON.getText());
            result.setCause(e.getMessage());
            logger.error("/user/getUserList", e);
        }
        return result;
    }

}
